<template>
  <ElCard>
    <BaseForm v-if="isReset" ref="userInfoForm" :type="type" />
    <div class="blog-user-info--btn">
      <ElButton type="primary" @click="submit">提交信息</ElButton>
      <ElButton type="info" @click="clean">重置信息</ElButton>
    </div>
  </ElCard>
</template>

<script setup lang="ts">
import { ElNotification } from 'element-plus'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

import $http from '@/api/http'
import BaseForm from '@/components/base/BaseForm.vue'
import FORM_MAP from '@/config/form.config'
import { useUser } from '@/store/user'
let user = useUser()
let router = useRouter()
let type = ref<string>('userInfo')
let isReset = ref<boolean>(true)
let userInfoForm = ref<typeof BaseForm | null>(null)
onMounted(() => {
  if (!userInfoForm.value) {
    return false
  }
  // 如果没有获取到组件, 首先看组件是否被渲染, 如果没有被渲染就观察是否为v-if条件约束
  getUserInfo()
})
async function submit() {
  let formUser = userInfoForm.value
  if (!formUser) {
    return false
  }
  let formData = formUser.form
  formUser.blogForm?.validate(async (valid) => {
    if (valid) {
      try {
        let result = await $http({
          type: 'putUserInfo',
          data: formData,
        })
        console.log(result)
        ElNotification({
          title: '成功',
          message: `${result.message}`,
          type: 'success',
        })
        user?.getUserInfo()
        router.push('/index')
      } catch (err) {
        ElNotification({
          title: '修改失败',
          message: err.message,
          type: 'error',
        })
        console.log(err)
        formUser.form = {}
      }
      // 这里只需要提交数据就行, 设置$state.token和userInfo 就交给http路由
      // alert('submit!');
    } else {
      console.log('error submit!!')
      return false
    }
  })
}
function clean() {
  // 实现组件的的重载
  // this.isReset = false
  // this.$nextTick(() => {
  //   this.isReset = true
  // })
  getUserInfo()
}
function getUserInfo() {
  // ref直接获取当前子组件的内容, 将form.config中的userInfo字段筛选出来
  userInfoForm.value.form =
    Object.fromEntries(
      Object.entries(user?.userInfo).filter(([key]) => {
        return FORM_MAP['userInfo'].find((item) => key === item.query || false)
      }),
    ) || {}
}
</script>
<style lang="less" scoped>
.blog-user-info--btn {
  box-sizing: border-box;
  display: flex;
  justify-content: flex-end;
  width: 100%;
  padding: 10px 180px;
}
</style>
